<template>
  <el-container>
    <el-header> 登录人</el-header>
    <el-container v-if="messages.length > 0">
      <el-aside width="300px">
        <div
          :class="['friends', { tabmes: index === isactive }]"
          ref="tabmessage"
          v-for="(item, index) in messages"
          :key="index"
          @click="tabmessage(index)"
          @contextmenu.prevent="openMenu($event, item, index)"
        >
          <ul
            v-show="visible"
            :style="{ left: left + 'px', top: top + 'px' }"
            class="contextmenu"
          >
            <li @click.stop="handleDelete">删除</li>
          </ul>
          <div class="friends-info">
            <div>
              <img
                src="https://img0.baidu.com/it/u=103721101,4076571305&fm=26&fmt=auto&gp=0.jpg"
                alt=""
              />
              <span class="info-name">{{ item.lastMsg.target }} </span>
            </div>
            <div v-show="item.unread" class="unread">{{ item.unread }}</div>
          </div>
          <div class="info-content">
            <div class="info-message">{{ item.lastMsg.text | gettext }}</div>
            <div class="info-time">{{ item.lastMsg.time | gettime }}</div>
          </div>
        </div>
      </el-aside>
      <el-main>
        <div class="content" v-if="messages.length > 0">
          <div class="info-name">{{ messages[isactive].lastMsg.target }}</div>
          <div class="chat-content" ref="msgContent">
            <div
              id="show_words"
              class="chat-ches"
              v-for="(item, index) in sessionsList"
              :key="index"
            >
              <div class="itemLeft" v-if="item.flow == 'in'">
                <div class="info" v-if="item.type == 'text'">
                  <div class="time">{{ item.time | formatDate }}</div>
                  <span class="info-content">{{ item.text }}</span>
                </div>
                <div class="info" v-else-if="item.type == 'image'">
                  <div class="time">{{ item.time | formatDate }}</div>
                  <a :href="item.file.url">
                    <img
                      :src="item.file.url"
                      alt=""
                      style="width: 80px; height: 80px"
                    />
                  </a>
                </div>
                <div class="info" v-else>
                  <div class="time">{{ item.time | formatDate }}</div>

                  <a :href="item.file.url" class="updatefile-left">
                    <span class="file-name">文件</span>
                    <span class="file-line"></span>
                    {{ item.file.name | filename }}
                  </a>
                </div>
              </div>
              <div
                class="itmeRight"
                v-else
                @contextmenu.prevent="openwithdraw($event, item, index)"
              >
                <ul
                  v-show="vis"
                  :style="{ left: left1 + 'px', top: top1 + 'px' }"
                  class="contextmenu"
                >
                  <li @click.stop="withdraw(item, index)">撤回</li>
                </ul>
                <div class="info" v-if="item.type == 'text'">
                  <div class="time">{{ item.time | formatDate }}</div>
                  <span class="info-content">{{ item.text }}</span>
                </div>
                <div class="info" v-else-if="item.type == 'image'">
                  <div class="time">{{ item.time | formatDate }}</div>
                  <a :href="item.file.url">
                    <img
                      :src="item.file.url"
                      alt=""
                      style="width: 80px; height: 80px"
                    />
                  </a>
                </div>
                <div class="info" v-else>
                  <div class="time">{{ item.time | formatDate }}</div>

                  <a :href="item.file.url" class="updatefile-left">
                    <span class="file-name">文件</span>
                    <span class="file-line"></span>
                    {{ item.file.name | filename }}
                  </a>
                </div>
              </div>
            </div>
          </div>
          <div class="content-line">
            <div class="expression">
              <el-popover
                ref="popover5"
                placement="top-start"
                width="360"
                v-model="showModal"
                class="expression-style"
              >
                <div class="emojiList">
                  <ul>
                    <li
                      v-for="(item, index) in emojiList"
                      :key="index"
                      @click="getBrow(index)"
                    >
                      {{ item }}
                    </li>
                  </ul>
                </div>
                <el-button slot="reference"
                  ><svg
                    t="1629873885883"
                    class="icon"
                    viewBox="0 0 1026 1024"
                    version="1.1"
                    xmlns="http://www.w3.org/2000/svg"
                    p-id="2760"
                    width="200"
                    height="200"
                  >
                    <path
                      d="M498.375111 792.149333c-154.197333 0-218.311111-138.609778-220.984889-144.526222l51.882667-23.324444c2.048 4.522667 51.256889 110.961778 169.073778 110.961778 126.122667-1.479111 174.108444-106.467556 176.071111-110.933333l51.996444 23.068444c-2.588444 5.831111-65.137778 142.848-225.052444 144.725333L498.375111 792.149333zM502.243556 924.444444c-211.740444 0-384-172.259556-384-384s172.259556-384 384-384 384 172.259556 384 384S713.984 924.444444 502.243556 924.444444zM502.243556 213.333333c-180.366222 0-327.111111 146.744889-327.111111 327.111111s146.744889 327.111111 327.111111 327.111111 327.111111-146.744889 327.111111-327.111111S682.638222 213.333333 502.243556 213.333333zM346.453333 473.770667c0 24.462222 19.825778 44.344889 44.344889 44.344889s44.344889-19.854222 44.344889-44.344889-19.825778-44.344889-44.344889-44.344889S346.453333 449.28 346.453333 473.770667zM568.661333 473.770667c0 24.462222 19.825778 44.344889 44.344889 44.344889s44.344889-19.854222 44.344889-44.344889-19.825778-44.344889-44.344889-44.344889S568.661333 449.28 568.661333 473.770667z"
                      p-id="2761"
                    ></path></svg
                ></el-button>
              </el-popover>
            </div>
            <div class="pics">
              <el-button size="small" class="pics-i" icon="el-icon-picture">
              </el-button>
              <input
                type="file"
                ref="upLoadImage"
                @change="upLoadImage"
                class="pics-input"
                v-if="isShowFile"
                accept="image/png,image/gif,image/jpeg"
              />
            </div>
            <div class="pics">
              <el-button size="small" class="pics-i" icon="el-icon-document">
              </el-button>
              <input
                type="file"
                ref="upLoadFile"
                @change="upLoadFile"
                class="pics-input"
              />
            </div>
          </div>
          <div class="content-input">
            <textarea class="chat-content" type="textarea" v-model.trim="text">
            </textarea>
            <button class="chat-button" @click="send">发送</button>
          </div>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>
<script>
import { formatDate } from "@utils/ind";
import SDK from "@/utils/chat/NIM_Web_SDK_v8.6.2.js";
const appDate = require("@/utils/config/emoji.json");
export default {
  name: "chat",
  data() {
    return {
      dataList: {}, // 初始化信息
      text: "", //发送的文字
      sessionsList: [], //聊天消息
      currentTime: Date.now(), //获取当前时间
      nim: {}, //初始化对象
      msg: {}, //消息对象
      messages: [], //会话列表渲染
      isactive: 0, //会话列表的下标
      emojiList: [], //表情
      showModal: false, //表情开关
      isShowFile: true, //是否展示文件，选择上传
      visible: false, //列表右击开关
      top: 0, //列表上距离
      left: 0, //列表右距离
      vis: false, //会话右击开关
      top1: 0, //会话上距离
      left1: 0, //会话右距离
      messagesindex: 0, //消息的下标
    };
  },
  created() {
    this.loadEmojis();
    var vm = this;
    vm.timer = setInterval(() => {
      var y = Date.now();
      vm.currentTime = y;
    }, 1000);
  },
  mounted() {
    this.init();
    // this.getLocalSessions();
  },
  beforeDestroy() {
    this.xiezai();
    if (this.timer) {
      clearInterval(this.timer); // 在Vue实例销毁前，清除我们的定时器
    }
  },
  methods: {
    //卸载im单列
    xiezai() {
      this.nim.disconnect({
        done: function (err) {
          console.log("实例已被完全清除");
        },
      });
    },
    //点击撤回会话消息
    withdraw(item) {
      let that = this;
      this.closewithdraw();

      this.nim.deleteMsg({
        msg: item,
        done: deleteMsgDone,
      });
      console.log("正在撤回消息", item);
      function deleteMsgDone(error) {
        console.log("撤回消息" + (!error ? "成功" : "失败"));
        if (error) {
          that.$message.error("超出撤回时间");
        } else {
          that.$message.success("成功撤回");
          that.$delete(that.sessionsList, that.messagesindex);
        }
      }
    },
    //关闭撤回右击事件
    closewithdraw() {
      this.vis = false;
    },
    //撤回右击事件
    openwithdraw(e, item, index) {
      this.messagesindex = index;

      let x = e.clientX;
      let y = e.clientY;
      this.top1 = y;
      this.left1 = x;
      this.vis = true;
    },

    //删除某个人的会话
    handleDelete() {
      this.$delete(this.messages, this.isactive);
      // console.log(this.messages[this.isactive].to);
      this.closeMenu();
      this.isactive = 0;
      this.nim.deleteSession({
        scene: "p2p",
        to: this.messages[this.isactive].to,
        done: deleteSessionDone,
      });
      function deleteSessionDone(error, obj) {
        console.log("删除服务器上的会话" + (!error ? "成功" : "失败"));
      }
      this.nim.deleteLocalSession({
        id: this.messages[this.isactive].id,
        done: deleteLocalSessionDone,
      });
      function deleteLocalSessionDone(error, obj) {
        console.log("删除本地会话" + (!error ? "成功" : "失败"), error, obj);
      }
    },
    //列表右击开启事件
    openMenu(e, item, index) {
      this.isactive = index;
      let x = e.clientX;
      let y = e.clientY;

      this.top = y;
      this.left = x;

      this.visible = true;
    },
    //列表右击关闭事件
    closeMenu() {
      this.visible = false;
    },
    //图片上传
    upLoadImage() {
      this.isShowFile = false;
      var that = this;
      const upLoadImage = this.$refs.upLoadImage;
      console.log(upLoadImage);
      this.nim.sendFile({
        scene: "p2p",
        to: this.messages[this.isactive].to,
        type: "image",
        fileInput: upLoadImage,
        done: sendMsgDone,
      });
      function sendMsgDone(error, msg) {
        console.log("图片上传", msg);
        that.sessionsList.push(msg);
        that.isShowFile = true;
      }
      // }
    },
    //文件上传
    upLoadFile() {
      var that = this;
      this.isShowFile = false;
      const upLoadFile = this.$refs.upLoadFile;
      console.log(upLoadFile);
      this.nim.sendFile({
        scene: "p2p",
        to: this.messages[this.isactive].to,
        type: "file",
        fileInput: upLoadFile,
        done: sendMsgDone,
      });
      function sendMsgDone(error, msg) {
        console.log("文件上传", msg);
        that.isShowFile = true;
        that.sessionsList.push(msg);
      }
    },
    //选中表情,将表情放到文本
    getBrow(index) {
      this.showModal = false;
      for (let i in this.emojiList) {
        if (index == i) {
          this.getBrowString = this.emojiList[index];
          this.text += this.getBrowString;
        }
      }
    },
    //加载表情
    loadEmojis() {
      for (let i in appDate) {
        this.emojiList.push(appDate[i].char);
      }
    },
    //切换会话人
    tabmessage(index) {
      let that = this;
      this.isactive = index;
      this.text = "";
      // console.log(this.messages[index]);
      this.nim.getHistoryMsgs({
        scene: "p2p",
        asc: true,
        to: this.messages[index].to,
        done: getHistoryMsgsDone,
      });
      function getHistoryMsgsDone(error, obj) {
        if (!error) {
          that.sessionsList = obj.msgs;
        }
      }
      this.nim.resetSessionUnread(
        this.messages[index].lastMsg.sessionId,
        (err, failId) => {
          if (err) {
            console.log("重置失败：", err, "失败的sessionid是", failId);
          }
        }
      );
    },
    //发送消息
    send() {
      let that = this;
      var msg = this.nim.sendText({
        scene: "p2p",
        to: this.messages[this.isactive].lastMsg.target,
        type: "text",
        text: this.text,
        done: sendMsgDone,
      });
      console.log("正在发送p2p text消息, id=" + msg.idClient);
      function sendMsgDone(error, msg) {
        that.sessionsList.push(msg);
        that.text = "";
        that.isactive = 0;
      }
    },
    //初始化
    init() {
      this.nim = SDK.NIM.getInstance({
        debug: true,
        appKey: "eb2c469bcb0ad0dae627da8624126a3f",
        account: "xiaohua",
        token: "c215d56b8fa208bd1c176e73cf6612c6",
        autoMarkRead: false,
        syncSessionUnread: true,
        rollbackDelMsgUnread: true,
        db: false,
        onconnect: this.onConnect,
        onwillreconnect: this.onWillReconnect,
        ondisconnect: this.onDisconnect,
        onerror: this.onError,
        onmsg: this.onMsg,
        onsessions: this.onSessions,
        onupdatesession: this.onUpdateSession,
      });
    },
    onMsg(msg) {
      console.log("消息收到了", msg.from);
      console.log(this.messages[this.isactive]);
      if (msg.from == this.messages[this.isactive].to) {
        console.log("消息收了");
        this.nim.resetSessionUnread(
          this.messages[this.isactive].lastMsg.sessionId,
          (err, failId) => {
            if (err) {
              console.log("重置失败：", err, "失败的sessionid是", failId);
            }
          }
        );
        this.sessionsList.push(msg);
      } else {
      }
    },

    onSessions(sessions) {
      console.log("收到会话列表", sessions);

      // sessions.filter((item) => {
      //   if (item.unread > 0) {
      //     this.messages = this.nim.mergeSessions(this.messages, item);
      //   }
      // });
      this.messages = this.nim.mergeSessions(this.messages, sessions);
      this.updateSessionsUI();
    },
    onUpdateSession(session) {
      // console.log("会话更新了", session);
      this.messages = this.nim.mergeSessions(this.messages, session);
      this.updateSessionsUI();
    },
    updateSessionsUI() {},
    onConnect() {
      // console.log("连接成功");
    },
    onWillReconnect(obj) {
      // 此时说明 SDK 已经断开连接, 请开发者在界面上提示用户连接已断开, 而且正在重新建立连接
      // console.log("即将重连");
      // console.log(obj.retryCount);
      // console.log(obj.duration);
    },
    onDisconnect(error) {
      // 此时说明 SDK 处于断开状态, 开发者此时应该根据错误码提示相应的错误信息, 并且跳转到登录页面
      // console.log("丢失连接");
      // console.log(error);
      if (error) {
        switch (error.code) {
          // 账号或者密码错误, 请跳转到登录页面并提示错误
          case 302:
            break;
          // 重复登录, 已经在其它端登录了, 请跳转到登录页面并提示错误
          case 417:
            break;
          // 被踢, 请提示错误后跳转到登录页面
          case "kicked":
            break;
          default:
            break;
        }
      }
    },
    onError(error) {
      // console.log(error);
    },
  },

  updated() {
    // this.scollBottom();
  },
  watch: {
    sessionsList() {
      this.$nextTick(() => {
        const dom = this.$refs.msgContent;
        if (!dom) return;
        dom.scrollTop = dom.scrollHeight;
      });
    },
    visible(value) {
      if (value) {
        document.body.addEventListener("click", this.closeMenu);
      } else {
        document.body.removeEventListener("click", this.closeMenu);
      }
    },
  },

  filters: {
    //对文件名字进行截取
    filename(text) {
      if (text.length > 6) {
        return text.slice(0, 6) + "...";
      }
      return text;
    },
    //对接收的消息进行截取
    gettext(text) {
      if (text.length > 6) {
        return text.slice(0, 6) + "...";
      }
      return text;
    },
    // 初始化发送消息的时间
    formatDate(time) {
      let times = new Date(time);
      return formatDate(times);
    },
    //初始化接收消息时间
    gettime(time) {
      let times = new Date(time);
      return formatDate(times);
    },
  },
};
</script>

<style lang="scss" scoped>
.el-header,
.el-footer {
  background-color: #b3c0d1;
  color: #333;
  text-align: center;
  line-height: 60px;
}
.el-aside {
  background-color: #ffffff;
  height: calc(100vh - 165px);
  overflow-y: auto;
  padding: 0 0 100px 0;
  border-right: 1px solid #eeeeee;
}
.el-main {
  height: calc(100vh - 165px);
  background-color: #ffffff;
  padding: 0;
}
.tabmes {
  background-color: #bfbec0;
}
.friends {
  cursor: pointer;
  // width: 280px;
  height: 80px;
  padding: 5px 25px 5px 15px;
  border-bottom: 1px solid #eeeeee;
  box-sizing: border-box;

  .friends-info {
    display: flex;
    justify-content: space-between;
    .unread {
      z-index: 1000;
      width: 20px;
      height: 20px;
      line-height: 20px; /* 数值与height相同，使数字垂直居中 */
      text-align: center;
      background-color: red;
      color: white;
      font-size: 12px;
      font-weight: 700;
      border-radius: 50%;
    }

    img {
      margin-right: 5px;
      width: 40px;
      height: 40px;
      border-radius: 50%;
    }
  }
  .info-content {
    display: flex;
    justify-content: space-between;
    color: #928ca9;
  }
}
.content {
  .info-name {
    line-height: 50px;
    text-align: center;
    border-bottom: 1px solid #eeeeee;
  }
  .chat-content {
    height: 375px;
    overflow-y: auto;
    .itemLeft {
      display: flex;
      padding: 10px 0 10px 0;
      .info {
        margin-left: 10px;
        .time {
          font-size: 12px;
          color: rgba(51, 51, 51, 0.8);
          margin: 0;
          height: 20px;
          line-height: 20px;
          margin-top: -5px;
        }
        .info-content {
          padding: 10px;
          font-size: 14px;
          background: #b5b5b6;
          position: relative;
          margin-top: 8px;
          top: 8px;
        }
        .info-content::before {
          position: absolute;
          left: -8px;
          top: 8px;
          content: "";
          border-right: 10px solid #b5b5b6;
          border-top: 8px solid transparent;
          border-bottom: 8px solid transparent;
        }
      }
    }
    .itmeRight {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 20px;
      .info {
        width: 90%;
        margin-left: 10px;
        text-align: right;
        .file-name {
          display: block;
          text-align: right;
          border-bottom: 1px solid #e0e0e0;
        }
        .time {
          font-size: 12px;
          color: rgba(51, 51, 51, 0.8);
          margin: 0;
          height: 20px;
          line-height: 20px;
          margin-top: -5px;
          margin-right: 10px;
        }
        .info-content {
          max-width: 70%;
          padding: 10px;
          font-size: 14px;
          float: right;
          margin-right: 10px;
          position: relative;
          margin-top: 8px;
          background: #b5b5b6;
          text-align: left;
        }
        .info-content::after {
          position: absolute;
          right: -8px;
          top: 8px;
          content: "";
          border-left: 10px solid #b5b5b6;
          border-top: 8px solid transparent;
          border-bottom: 8px solid transparent;
        }
      }
    }
  }
  .content-line {
    height: 30px;
    background-color: #eeeeee;
    display: flex;

    .expression {
      width: 30px;
      height: 30px;
      .el-button {
        padding: 0 0;
      }
      .icon {
        width: 100%;
        height: 100%;
        z-index: 10000;
      }
    }
  }
}
.pics {
  margin-left: 5px;
  width: 30px;
  height: 30px;
  overflow: hidden;
  box-sizing: border-box;
  position: relative;

  .el-button {
    font-size: 28px;
  }
  .pics-input {
    display: block;
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: transparent !important ;
    opacity: 0;
  }
  .el-button {
    background: #eeeeee;
    padding: 0 0;
  }
}
.emojiList {
  width: 100%;
  height: 200px;
  position: absolute;
  z-index: 100;
  bottom: 0px;
  overflow: scroll;
  background-color: white;
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    li {
      cursor: pointer;
      width: 10%;
      font-size: 26px;
      list-style: none;
      text-align: center;
    }
  }
}
.content-input {
  width: 100%;
  height: 100px;
  position: relative;
  .chat-content {
    width: 100%;
    height: 100%;
    outline: none;
  }
  .chat-button {
    position: absolute;
    right: 0;
    bottom: 0;
    width: 100px;
    height: 30px;
  }
}
.updatefile-left {
  display: inline-block;
  height: 70px;
  width: 140px;
  padding: 10px 10px;
  background-color: #ffffff;
  box-shadow: 2px 2px 1px 2px #928ca9;
  color: black;
}
.contextmenu {
  margin: 0;
  background: #fff;
  z-index: 3000;
  position: fixed;
  list-style-type: none;
  padding: 5px 0;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 400;
  color: #333;
  box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);
  li {
    margin: 0;
    padding: 7px 16px;
    cursor: pointer;
  }
  li:hover {
    background-color: rgb(3, 125, 243);
    color: white;
  }
}
</style>